package com.reggie.controller;

import com.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.img_path}")
    private  String path;
    @Value("${reggie.img_path_linux}")
    private  String path_linux;
    /**
     * 下载图片
     *
     * @param name
     * @param response
     */
    @RequestMapping("/download")
    public void download(String name, HttpServletResponse response) {
        if (!new File(path).exists())
            path=path_linux;
        //放在try里面可以自动释放资源
        try (FileInputStream fileInputStream = new FileInputStream(new File(path + name));
             ServletOutputStream outputStream = response.getOutputStream()) {
            //使用工具类简化输入流转输出流
            StreamUtils.copy(fileInputStream, outputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传图片到服务器
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        if (!new File(path).exists())
            path=path_linux;
        //获取文件名
        String filename = file.getOriginalFilename();
        //以最后一个.开始分割，拿到后缀
        String s = filename.substring(filename.lastIndexOf("."));
        String name = UUID.randomUUID().toString() + s;
        try {
            //将图片另存到本地
            file.transferTo(new File(path + name));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(name);
    }
}
